# $Id: service.py 14 2008-08-21 21:31:25Z jkingry $

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson

from data import *

class ApplicationError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
	
class BaseHandler(webapp.RequestHandler):
    def __init__(self):
        self.load_account = True
    def get(self):
        try:
            if self.load_account:	 
                account_key = self.request.get('account')
                account = db.get(account_key)
            
                if account is None:
                    raise ApplicationError, "Invalid account"     
            
            result = self.run(account)
            self.response.out.write(simplejson.dumps(result))
        except ApplicationError, x:
            self.set_status(500, str(x))        
        
    def run(self, account):
        pass

class AppServerListHandler(BaseHandler):
    def __init__(self):
        self.load_account = False
                
    def run(self, account):       
        servers_query = AppServer.all().filter("active =", True).order('-created')
        
        servers = servers_query.fetch(10)
        
        return [ { 
                    "server_key": str(s.key()),
                    "ip_address": s.ip_address
                 }
                 for s in servers
               ]
 
class AppServerCreateHandler(BaseHandler):
    def run(self, account):        
        name = self.request.get('name')        
        
        server = AppServer.all().filter('name =', name).get()
        if server is None:	        
            ip_address = self.request.remote_addr
            
            server_key = new_server_key()
                        
            server = AppServer(key_name = server_key, name = name, owner = account, ip_address = ip_address)
            server.put()
            
            return { 'ip_address': ip_address, 'server_key': str(server.key()) }
        else:
            self.redirect("/service/update?account=%s&server=%s&active=true" % (account.key(), server.key()))
	
class AppServerDeleteHandler(BaseHandler):
    def run(self, account):        
        server_key = self.request.get('server')

        server = db.get(server_key)

        if server is None: 
            self.error(500)
            return

        if server.owner.key() != account.key():
            self.error(500)
            return

        server.delete()

        return "Server Deleted"
    
class AppServerUpdateHandler(BaseHandler):
    def run(self, account):        
        server_key = self.request.get('server')
        active = parse_boolean(self.request.get('active'))
        ip_address = self.request.remote_addr
    
        server = db.get(server_key)

        if server is None:
            self.error(500)
            return
            
        if server.owner.key() != account.key():
            self.error(500)
            return

        server.ip_address = ip_address
        server.active = active
        server.put()
        
        return { 'ip_address': ip_address, 'server_key': str(server.key()) }

class AppServerSuccessHandler(BaseHandler):
    def get(self): 
        ip_address = self.request.get('ip_address')
        server_success(ip_address)
        
        self.response.out.write("Success")

class AppServerFailureHandler(BaseHandler):
    def get(self):       
        server_key = self.request.get('ip_address')
        server_failure(ip_address)
        
        self.response.out.write("Success")


application = webapp.WSGIApplication(
                                     [
                                      ('/service/list', AppServerListHandler),
                                      ('/service/create', AppServerCreateHandler),
                                      ('/service/update', AppServerUpdateHandler),
                                      ('/service/delete', AppServerDeleteHandler),
                                      ('/service/success', AppServerSuccessHandler),
                                      ('/service/failure', AppServerFailureHandler)
                                     ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()